package com.etung.iot.demo.storage;

import com.etung.iot.demo.dao.RealDataMapper;
import com.etung.iot.demo.modles.RealData;
import com.etung.iot.demo.modles.StorageEntity;
import com.etung.iot.demo.storage.constorage.TriggerConditionStoreRule;
import com.etung.iot.demo.utils.BigDecimalUtil;
import com.etung.iot.demo.utils.SpringContextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

@Component
@Storage(StorageConstant.CHANGE_STORAGE)
public class RangeStoreRule implements StorageHandler{
    @Autowired
    private StorageRuleUtil storageRuleUtil;
    @Autowired
    private RealDataMapper realDataMapper;
    @Autowired
    private ConStorageSelector conStorageSelector;


    @Override
    public void handler(RealData realData) {
        String imei = realData.getImei();
        int varId = realData.getVarId();
        StorageEntity storageRule = storageRuleUtil.getStorageRule(imei, varId);
        String value = storageRuleUtil.getLastStoreValue(imei,varId);
        storageRuleUtil.saveLastStoreValue(realData.getImei(),realData.getVarId(),realData.getValue());
        Boolean isNeedSave = false;
        if (StringUtils.isEmpty(value)){ //如果上一次是空,此次有值，则保存
            if(!StringUtils.isEmpty(realData.getValue())){
                isNeedSave = true;
            }
        }else{
            if(!StringUtils.isEmpty(realData.getValue())){
                BigDecimal lastValue = BigDecimalUtil.getBigDecimal(value);
                BigDecimal currentValue = BigDecimalUtil.getBigDecimal(realData.getValue());
                if(!StringUtils.isEmpty(storageRule.getUpLimit())){
                    BigDecimal upLimit = BigDecimalUtil.getBigDecimal(storageRule.getUpLimit());
                    if (currentValue.subtract(lastValue).compareTo(upLimit) >=0){
                        isNeedSave = true;
                    }
                }
                if(!StringUtils.isEmpty(storageRule.getLowerLimit())){
                    BigDecimal lowLimit = BigDecimalUtil.getBigDecimal(storageRule.getLowerLimit());
                    if(currentValue.subtract(lastValue).compareTo(lowLimit) <= 0){
                        isNeedSave = true;
                    }
                }
            }

        }
        if(isNeedSave){
            realDataMapper.insert(realData);
        }else{
            conStorageSelector.saveConditionRealData(realData);
        }

    }
}
